package cn.pink.common.support.tools.vertx;

import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.shareddata.Lock;
import lombok.Getter;

/**
 * vertx 插件
 * @Author: pink
 * @Date: 2022/6/9 18:12
 */
public class VertxTool {
    private static VertxTool tool = new VertxTool();

    private VertxTool() {

    }

    public static VertxTool getInstance() {
        return tool;
    }

    @Getter
    private Vertx vertx;

    public void init(Vertx vertx) {
        this.vertx = vertx;
    }

    /**
     * 分布式锁
     * TODO 需要完善  考虑幂等性 统一写法
     */
    public Future<Lock> tryLock(String name) {
        Promise<Lock> promise = Promise.promise();

        vertx.sharedData().getLock(name)
                .onSuccess(promise::complete)
                .onFailure(e -> promise.fail(e.getMessage()));

        return promise.future();
    }
}
